All files / web/src/app/practice/[studentId]/summary SummaryClient.tsx

0% Statements 0/714
0% Branches 0/1
0% Functions 0/1
0% Lines 0/714

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use client'

import { useQuery } from '@tanstack/react-query'
import dynamic from 'next/dynamic'
import { useRouter } from 'next/navigation'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { PageWithNav } from '@/components/PageWithNav'
// Direct imports instead of barrel to reduce compilation scope
import { AllProblemsSection } from '@/components/practice/AllProblemsSection'
import { calculateAutoPauseInfo } from '@/components/practice/autoPauseCalculator'
import { ContentBannerSlot, ProjectingBanner } from '@/components/practice/BannerSlots'
import { CameraModal } from '@/components/practice/CameraModal'
import { DocumentAdjustmentModal } from '@/components/practice/DocumentAdjustmentModal'
import type { OfflineAttachment } from '@/components/practice/OfflineWorkSection'
import { OfflineWorkSection } from '@/components/practice/OfflineWorkSection'
import type { PhotoViewerEditorPhoto } from '@/components/practice/PhotoViewerEditor'
import { PracticeSubNav } from '@/components/practice/PracticeSubNav'
import { ProblemsToReviewPanel } from '@/components/practice/ProblemsToReviewPanel'
import type { ScrollspySection } from '@/components/practice/ScrollspyNav'
import { ScrollspyNav } from '@/components/practice/ScrollspyNav'
import { SessionHero } from '@/components/practice/SessionHero'
import { SessionSongPlayer } from '@/components/practice/SessionSongPlayer'
import { SkillsPanel } from '@/components/practice/SkillsPanel'

// Dynamic import: StartPracticeModal → SkillTutorialLauncher → TutorialPlayer → @soroban/abacus-react
// This breaks the dependency chain that pulls the entire abacus library into page.js
const StartPracticeModal = dynamic(
  () => import('@/components/practice/StartPracticeModal').then((m) => m.StartPracticeModal),
  { ssr: false }
)

import {
  filterProblemsNeedingAttention,
  getProblemsWithContext,
} from '@/components/practice/sessionSummaryUtils'
import type { ProblemCorrection } from '@/components/worksheet-parsing'
import type { ParsingStatus } from '@/db/schema/practice-attachments'

// Dynamic imports for heavy components (OpenCV, PhotoViewerEditor)
// These are loaded on-demand to reduce initial compilation time
const PhotoViewerEditor = dynamic(
  () => import('@/components/practice/PhotoViewerEditor').then((m) => m.PhotoViewerEditor),
  { ssr: false }
)

const VisionRecordingPlayer = dynamic(
  () => import('@/components/vision/VisionRecordingPlayer').then((m) => m.VisionRecordingPlayer),
  { ssr: false }
)

import { useToast } from '@/components/common/ToastContext'
import { GuestProgressBanner, recordGuestSession } from '@/components/GuestProgressBanner'
import {
  SessionModeBannerProvider,
  useSessionModeBanner,
} from '@/contexts/SessionModeBannerContext'
import { useTheme } from '@/contexts/ThemeContext'
import { WorksheetParsingProvider } from '@/contexts/WorksheetParsingContext'
import type { Player } from '@/db/schema/players'
import type { SessionPlan, SlotResult } from '@/db/schema/session-plans'
import { usePhotoManagement } from '@/hooks/usePhotoManagement'
import { usePhotoViewer } from '@/hooks/usePhotoViewer'
import { canUploadPhotos, usePlayerAccess } from '@/hooks/usePlayerAccess'
import { useSessionMode } from '@/hooks/useSessionMode'
import { useSessionRecording } from '@/hooks/useSessionRecording'
import {
  getPendingAttachmentId,
  useApproveAndCreateSession,
  useCancelParsing,
  useInitializeReview,
  useSubmitCorrections,
  useUnapproveWorksheet,
  useUpdateReviewProgress,
} from '@/hooks/useWorksheetParsing'
import { computeBktFromHistory, type SkillBktResult } from '@/lib/curriculum/bkt'
import type { ProblemResultWithContext } from '@/lib/curriculum/session-planner'
import { api } from '@/lib/queryClient'
import { attachmentKeys } from '@/lib/queryKeys'
import type { SessionAttachmentResponse } from '@/types/attachments'
import { css } from '../../../../../styled-system/css'

// Combined height of sticky elements above content area
// Main nav (80px) + Sub-nav (~56px with padding)
const STICKY_HEADER_OFFSET = 136

// ============================================================================
// Helper Component for Banner Action Registration
// ============================================================================

/**
 * Registers the action callback with the banner context.
 * Must be inside SessionModeBannerProvider to access context.
 */
function BannerActionRegistrar({ onAction }: { onAction: () => void }) {
  const { setOnAction } = useSessionModeBanner()

  useEffect(() => {
    setOnAction(onAction)
  }, [onAction, setOnAction])

  return null
}

interface SummaryClientProps {
  studentId: string
  player: Player
  session: SessionPlan | null
  /** Average seconds per problem from recent sessions */
  avgSecondsPerProblem?: number
  /** Problem history for BKT computation in weak skills targeting */
  problemHistory?: ProblemResultWithContext[]
  /** Whether we just transitioned from active practice to this summary */
  justCompleted?: boolean
  /** Previous session accuracy (0-1) for trend comparison */
  previousAccuracy?: number | null
  /** Whether session song generation is available (feature flag + family tier) */
  songEnabled?: boolean
}

/**
 * Summary Client Component
 *
 * Displays the session results and provides navigation options.
 * Handles three cases:
 * - In-progress session: shows partial results
 * - Completed session: shows full results
 * - No session: shows empty state
 */
export function SummaryClient({
  studentId,
  player,
  session,
  avgSecondsPerProblem = 40,
  problemHistory,
  justCompleted = false,
  previousAccuracy = null,
  songEnabled = false,
}: SummaryClientProps) {
  const { resolvedTheme } = useTheme()
  const isDark = resolvedTheme === 'dark'
  const { showSuccess, showError } = useToast()
  const router = useRouter()

  // Record guest session completion for "save your progress" prompts
  useEffect(() => {
    if (justCompleted) {
      recordGuestSession()
    }
  }, [justCompleted])

  // UI state
  const [showStartPracticeModal, setShowStartPracticeModal] = useState(false)

  // Photo management hook (camera, upload, drag-drop, document adjustment)
  const photoManagement = usePhotoManagement({
    studentId,
    sessionId: session?.id,
    onError: (msg) => showError(msg),
  })

  // Photo viewer hook (modal state)
  const photoViewer = usePhotoViewer()

  // Session mode - single source of truth for session planning decisions
  const { data: sessionModeData, isLoading: isLoadingSessionMode } = useSessionMode(studentId)
  const sessionMode = sessionModeData?.sessionMode
  const comfortLevel = sessionModeData?.comfortLevel
  const comfortByMode = sessionModeData?.comfortByMode

  // Player access - pre-flight authorization check for upload capability
  const { data: playerAccess } = usePlayerAccess(studentId)
  const canUpload = canUploadPhotos(playerAccess)

  // Vision recording for this session (if available)
  const { data: recordingData, isLoading: isLoadingRecording } = useSessionRecording(
    studentId,
    session?.id ?? ''
  )

  // Fetch attachments for this session (includes parsing data)
  const { data: attachmentsData } = useQuery({
    queryKey: session?.id ? attachmentKeys.session(studentId, session.id) : ['no-session'],
    queryFn: async (): Promise<{
      attachments: SessionAttachmentResponse[]
    }> => {
      if (!session?.id) return { attachments: [] }
      const res = await api(`curriculum/${studentId}/sessions/${session.id}/attachments`)
      if (!res.ok) return { attachments: [] }
      return res.json() as Promise<{
        attachments: SessionAttachmentResponse[]
      }>
    },
    enabled: !!session?.id,
  })

  // Map API response to OfflineAttachment type (cast parsingStatus and rawParsingResult)
  const attachments: OfflineAttachment[] = (attachmentsData?.attachments ?? []).map((att) => ({
    id: att.id,
    url: att.url,
    parsingStatus: att.parsingStatus as ParsingStatus | null,
    rawParsingResult: att.rawParsingResult as OfflineAttachment['rawParsingResult'],
    needsReview: att.needsReview,
    sessionCreated: att.sessionCreated,
    reviewProgress: att.reviewProgress as OfflineAttachment['reviewProgress'],
  }))

  // Worksheet parsing mutations
  const cancelParsing = useCancelParsing(studentId, session?.id ?? '')

  // Approve and create session mutation
  const approveAndCreateSession = useApproveAndCreateSession(studentId, session?.id ?? '')

  // Submit corrections mutation
  const submitCorrections = useSubmitCorrections(studentId, session?.id ?? '')

  // Initialize review progress mutation (for starting the review workflow)
  const initializeReview = useInitializeReview(studentId, session?.id ?? '')

  // Unapprove/revert worksheet mutation (for testing/corrections)
  const unapproveWorksheet = useUnapproveWorksheet(studentId, session?.id ?? '')

  // Update review progress (for focus review mode individual problem updates)
  const updateReviewProgress = useUpdateReviewProgress(studentId, session?.id ?? '')

  // Map attachments to PhotoViewerEditorPhoto type for the viewer
  const viewerPhotos: PhotoViewerEditorPhoto[] = (attachmentsData?.attachments ?? []).map(
    (att): PhotoViewerEditorPhoto => ({
      id: att.id,
      url: att.url,
      originalUrl: att.originalUrl,
      corners: att.corners,
      rotation: att.rotation,
      parsingStatus: att.parsingStatus as PhotoViewerEditorPhoto['parsingStatus'],
      // Prefer approvedResult (user-corrected) over rawParsingResult (original LLM output)
      problemCount: (
        (att.approvedResult ?? att.rawParsingResult) as {
          problems?: unknown[]
        } | null
      )?.problems?.length,
      sessionCreated: att.sessionCreated,
      rawParsingResult:
        (att.approvedResult ?? att.rawParsingResult)
          ? ((att.approvedResult ?? att.rawParsingResult) as NonNullable<
              PhotoViewerEditorPhoto['rawParsingResult']
            >)
          : null,
      llm: att.llm as PhotoViewerEditorPhoto['llm'],
    })
  )

  const hasPhotos = attachments.length > 0

  const isInProgress = session?.startedAt && !session?.completedAt

  // Check if session has actual problems (not just photos)
  const sessionResults = (session?.results ?? []) as SlotResult[]
  const hasProblems = sessionResults.length > 0

  // Compute current session accuracy for guest banner
  const sessionAccuracy = useMemo(() => {
    if (sessionResults.length === 0) return null
    const correct = sessionResults.filter((r) => r.isCorrect).length
    return correct / sessionResults.length
  }, [sessionResults])

  // Compute BKT from problem history to get skill masteries
  const skillMasteries = useMemo<Record<string, SkillBktResult>>(() => {
    if (!problemHistory || problemHistory.length === 0) {
      return {}
    }
    const bktResult = computeBktFromHistory(problemHistory)
    // Convert array to record for easy lookup
    return Object.fromEntries(bktResult.skills.map((skill) => [skill.skillId, skill]))
  }, [problemHistory])

  // Calculate auto-pause info for determining slow problems
  const autoPauseInfo = useMemo(() => {
    if (!hasProblems)
      return {
        threshold: 0,
        stats: { sampleCount: 0, meanMs: 0, stdDevMs: 0 },
      }
    return calculateAutoPauseInfo(sessionResults)
  }, [hasProblems, sessionResults])

  // Get problems that need attention (incorrect, slow, or used heavy help)
  const problemsNeedingAttention = useMemo(() => {
    if (!session || !hasProblems) return []
    const problemsWithContext = getProblemsWithContext(session)
    return filterProblemsNeedingAttention(problemsWithContext, autoPauseInfo.threshold)
  }, [session, hasProblems, autoPauseInfo.threshold])

  // Define scrollspy sections to match plan: Overview | Skills | Review | Evidence
  const scrollspySections = useMemo<ScrollspySection[]>(() => {
    const sections: ScrollspySection[] = []
    if (hasProblems) {
      sections.push({ id: 'overview', label: 'Overview' })
      sections.push({ id: 'skills', label: 'Skills' })
      sections.push({ id: 'review', label: 'Review' })
    }
    sections.push({ id: 'evidence', label: 'Evidence' })
    return sections
  }, [hasProblems])

  // Handle practice again - show the start practice modal
  const handlePracticeAgain = useCallback(() => {
    setShowStartPracticeModal(true)
  }, [])

  // Determine header text based on session state
  // Only shown for photo-only sessions and no-session state
  // (SessionSummary handles its own header for sessions with problems)
  const headerTitle = isInProgress
    ? 'Session In Progress'
    : session
      ? 'Practice Session'
      : 'No Sessions Yet'

  const headerSubtitle = isInProgress
    ? `${player.name} is currently practicing`
    : session
      ? hasPhotos
        ? 'Photos from practice'
        : 'Add photos from practice'
      : `${player.name} hasn't completed any sessions yet`

  return (
    <SessionModeBannerProvider sessionMode={sessionMode ?? null} isLoading={isLoadingSessionMode}>
      <WorksheetParsingProvider playerId={studentId} sessionId={session?.id ?? ''}>
        <BannerActionRegistrar onAction={handlePracticeAgain} />
        {/* Single ProjectingBanner renders at provider level */}
        <ProjectingBanner />
        <PageWithNav>
          {/* Practice Sub-Navigation */}
          <PracticeSubNav student={player} pageContext="summary" />

          {/* Guest save-your-progress banner */}
          <GuestProgressBanner
            sessionAccuracy={sessionAccuracy}
            previousAccuracy={previousAccuracy}
          />

          <main
            data-component="practice-summary-page"
            className={css({
              minHeight: '100vh',
              backgroundColor: isDark ? 'gray.900' : 'gray.50',
              paddingTop: '2rem',
              paddingLeft: '2rem',
              paddingRight: '2rem',
              paddingBottom: '2rem',
            })}
          >
            <div
              className={css({
                maxWidth: '1400px',
                margin: '0 auto',
              })}
            >
              {/* Header - only show when SessionSummary won't (photo-only or no session) */}
              {!hasProblems && (
                <header
                  className={css({
                    textAlign: 'center',
                    marginBottom: '2rem',
                  })}
                >
                  <h1
                    className={css({
                      fontSize: '1.5rem',
                      fontWeight: 'bold',
                      color: isDark ? 'white' : 'gray.800',
                      marginBottom: '0.5rem',
                    })}
                  >
                    {headerTitle}
                  </h1>
                  <p
                    className={css({
                      fontSize: '0.875rem',
                      color: isDark ? 'gray.400' : 'gray.600',
                    })}
                  >
                    {headerSubtitle}
                  </p>
                </header>
              )}

              {/* Session mode banner - renders in-flow, projects to nav on scroll */}
              <ContentBannerSlot
                stickyOffset={STICKY_HEADER_OFFSET}
                className={css({ marginBottom: '1.5rem' })}
              />

              {/* Mobile scrollspy navigation */}
              {session && scrollspySections.length > 1 && (
                <ScrollspyNav
                  sections={scrollspySections}
                  topOffset={STICKY_HEADER_OFFSET + 60}
                  isDark={isDark}
                />
              )}

              {/* Session Summary or Empty State */}
              {session ? (
                <>
                  {/* Responsive two-column layout for desktop
                    Plan: Left (~45%) = Hero + Evidence, Right (~55%) = Skills + Review */}
                  <div
                    data-layout="summary-grid"
                    className={css({
                      display: 'grid',
                      gap: '1.5rem',
                      // Mobile: single column
                      gridTemplateColumns: '1fr',
                      // Desktop (1200px+): two columns per plan spec
                      '@media (min-width: 1200px)': {
                        gridTemplateColumns: hasProblems ? '45% 55%' : '1fr',
                        gap: '2rem',
                        alignItems: 'start',
                      },
                    })}
                  >
                    {/* Left column: Hero + Evidence (Photos + All Problems) */}
                    <div
                      data-column="hero-evidence"
                      className={css({
                        display: 'flex',
                        flexDirection: 'column',
                        gap: '1.5rem',
                        // On mobile, this appears first
                        order: 1,
                      })}
                    >
                      {/* Session Hero - celebration header, stats, trend */}
                      {hasProblems && (
                        <div data-scrollspy-section="overview">
                          <SessionHero
                            plan={session}
                            studentName={player.name}
                            justCompleted={justCompleted}
                            previousAccuracy={previousAccuracy ?? null}
                            isDark={isDark}
                          />
                        </div>
                      )}

                      {/* Session Song Player — AI-generated celebration song */}
                      {songEnabled && session?.id && (
                        <SessionSongPlayer
                          playerId={studentId}
                          planId={session.id}
                          triggerFallback={justCompleted}
                        />
                      )}

                      {/* Vision recording playback (if available) */}
                      {recordingData?.hasRecording &&
                        recordingData.recording?.status === 'ready' &&
                        recordingData.recording?.videoUrl &&
                        recordingData.recording?.durationMs && (
                          <div
                            data-scrollspy-section="recording"
                            className={css({
                              mb: 6,
                              px: { base: 4, md: 0 },
                            })}
                          >
                            <h3
                              className={css({
                                fontSize: 'lg',
                                fontWeight: 'semibold',
                                color: isDark ? 'gray.100' : 'gray.900',
                                mb: 3,
                              })}
                            >
                              Session Recording
                            </h3>
                            <VisionRecordingPlayer
                              videoUrl={recordingData.recording.videoUrl}
                              durationMs={recordingData.recording.durationMs}
                              problemMarkers={recordingData.recording.problemMarkers}
                            />
                          </div>
                        )}

                      {/* Evidence section: Photos + All Problems */}
                      <div data-scrollspy-section="evidence">
                        <OfflineWorkSection
                          attachments={attachments}
                          fileInputRef={photoManagement.fileInputRef}
                          isUploading={photoManagement.isUploading}
                          uploadError={photoManagement.uploadError}
                          deletingId={photoManagement.deletingId}
                          parsingId={null}
                          dragOver={photoManagement.dragOver}
                          isDark={isDark}
                          canUpload={canUpload}
                          studentId={studentId}
                          studentName={player.name}
                          classroomId={playerAccess?.classroomId}
                          onFileSelect={photoManagement.handleFileSelect}
                          onDrop={photoManagement.handleDrop}
                          onDragOver={photoManagement.handleDragOver}
                          onDragLeave={photoManagement.handleDragLeave}
                          onOpenCamera={photoManagement.openCamera}
                          onOpenViewer={photoViewer.open}
                          onDeletePhoto={photoManagement.deletePhoto}
                          onCancelParsing={(attachmentId) => cancelParsing.mutate(attachmentId)}
                          reparsingPhotoId={null}
                          onInitializeReview={async (attachmentId) => {
                            await initializeReview.mutateAsync(attachmentId)
                          }}
                          initializingReviewId={getPendingAttachmentId(initializeReview)}
                          onApproveAll={async (attachmentId) => {
                            try {
                              const result = await approveAndCreateSession.mutateAsync(attachmentId)
                              showSuccess(
                                `Added ${result.problemCount} problems to session (${result.correctCount}/${result.problemCount} correct)`
                              )
                            } catch (err) {
                              showError(
                                err instanceof Error ? err.message : 'Failed to approve worksheet'
                              )
                            }
                          }}
                          approvingId={getPendingAttachmentId(approveAndCreateSession)}
                          onUnapprove={async (attachmentId) => {
                            try {
                              const result = await unapproveWorksheet.mutateAsync(attachmentId)
                              showSuccess(result.message)
                            } catch (err) {
                              showError(
                                err instanceof Error ? err.message : 'Failed to revert worksheet'
                              )
                            }
                          }}
                          unaprovingId={getPendingAttachmentId(unapproveWorksheet)}
                        />
                        {/* All Problems - complete session listing */}
                        {hasProblems && (
                          <div className={css({ marginTop: '1.5rem' })}>
                            <AllProblemsSection plan={session} isDark={isDark} />
                          </div>
                        )}
                      </div>
                    </div>

                    {/* Right column: Skills + Review */}
                    {hasProblems && (
                      <div
                        data-column="skills-review"
                        className={css({
                          display: 'flex',
                          flexDirection: 'column',
                          gap: '1.5rem',
                          // On mobile, this appears second
                          order: 2,
                          '@media (min-width: 1200px)': {
                            position: 'sticky',
                            top: '160px', // Below nav
                          },
                        })}
                      >
                        {/* Skills Panel */}
                        <div data-scrollspy-section="skills">
                          <SkillsPanel results={sessionResults} isDark={isDark} />
                        </div>

                        {/* Problems to Review */}
                        <div data-scrollspy-section="review">
                          <ProblemsToReviewPanel
                            problems={problemsNeedingAttention}
                            results={sessionResults}
                            skillMasteries={skillMasteries}
                            totalProblems={sessionResults.length}
                            isDark={isDark}
                          />
                        </div>
                      </div>
                    )}
                  </div>
                </>
              ) : (
                <div
                  className={css({
                    padding: '3rem',
                    textAlign: 'center',
                    backgroundColor: isDark ? 'gray.800' : 'white',
                    borderRadius: '16px',
                    border: '1px solid',
                    borderColor: isDark ? 'gray.700' : 'gray.200',
                  })}
                >
                  <p
                    className={css({
                      fontSize: '1.125rem',
                      color: isDark ? 'gray.400' : 'gray.600',
                    })}
                  >
                    Start a practice session to see results here.
                  </p>
                </div>
              )}
            </div>
          </main>

          {/* Start Practice Modal */}
          {showStartPracticeModal && sessionMode && (
            <StartPracticeModal
              studentId={studentId}
              studentName={player.name}
              focusDescription={sessionMode.focusDescription}
              sessionMode={sessionMode}
              comfortLevel={comfortLevel}
              comfortByMode={comfortByMode}
              avgSecondsPerProblem={avgSecondsPerProblem}
              existingPlan={null}
              problemHistory={problemHistory}
              onClose={() => setShowStartPracticeModal(false)}
              onStarted={() => setShowStartPracticeModal(false)}
            />
          )}

          {/* Photo Viewer/Editor */}
          <PhotoViewerEditor
            photos={viewerPhotos}
            initialIndex={photoViewer.index}
            initialMode={photoViewer.mode}
            isOpen={photoViewer.isOpen}
            onClose={photoViewer.close}
            onEditConfirm={photoManagement.handlePhotoEditConfirm}
            onApprove={async (attachmentId) => {
              try {
                const result = await approveAndCreateSession.mutateAsync(attachmentId)
                showSuccess(
                  'Session Updated',
                  `${result.problemCount} problem${result.problemCount === 1 ? '' : 's'} added to session`
                )
                // Close the viewer and refresh the page to show updated session data
                photoViewer.close()
                router.refresh()
              } catch (error) {
                showError(
                  'Failed to create session',
                  error instanceof Error ? error.message : 'Please try again'
                )
              }
            }}
            approvingPhotoId={getPendingAttachmentId(approveAndCreateSession)}
            onSubmitCorrection={async (attachmentId, correction) => {
              await submitCorrections.mutateAsync({
                attachmentId,
                corrections: [correction],
              })
            }}
            savingProblemNumber={
              submitCorrections.isPending
                ? ((
                    submitCorrections.variables as {
                      attachmentId: string
                      corrections: ProblemCorrection[]
                    }
                  )?.corrections?.[0]?.problemNumber ?? null)
                : null
            }
            onCancelParsing={(attachmentId) => cancelParsing.mutate(attachmentId)}
            onApproveProblem={async (photoId, problemIndex) => {
              await updateReviewProgress.mutateAsync({
                attachmentId: photoId,
                problemUpdate: {
                  index: problemIndex,
                  reviewStatus: 'approved',
                },
              })
            }}
            onFlagProblem={async (photoId, problemIndex) => {
              await updateReviewProgress.mutateAsync({
                attachmentId: photoId,
                problemUpdate: { index: problemIndex, reviewStatus: 'flagged' },
              })
            }}
            onFocusReviewComplete={async (photoId) => {
              // Mark review as completed and trigger approval flow
              await updateReviewProgress.mutateAsync({
                attachmentId: photoId,
                status: 'completed',
              })
              showSuccess('Review complete', 'All problems have been reviewed')
            }}
          />

          {/* Fullscreen Camera Modal */}
          <CameraModal
            isOpen={photoManagement.showCamera}
            onClose={photoManagement.closeCamera}
            onCapture={photoManagement.handleCameraCapture}
          />

          {/* File Upload Adjustment Modal */}
          <DocumentAdjustmentModal
            state={photoManagement.adjustmentState}
            queueLength={photoManagement.queueLength}
            opencvRef={photoManagement.opencvRef}
            detectQuadsInImage={photoManagement.detectQuadsInImage}
            onConfirm={photoManagement.handleAdjustmentConfirm}
            onSkip={photoManagement.handleAdjustmentSkip}
            onCancel={photoManagement.handleAdjustmentCancel}
          />
        </PageWithNav>
      </WorksheetParsingProvider>
    </SessionModeBannerProvider>
  )
}